package shop.controller.manage.organize;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.BaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.bean.ManageContainer;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.sms.SMS;
import shop.core.plugins.sms.SMSVerifyCodeResult;
import shop.core.util.MD5;
import shop.core.util.QRcodeUtils;
import shop.services.manage.account.AccountService;
import shop.services.manage.account.bean.Account;
import shop.services.manage.offline.OfflineService;
import shop.services.manage.offline.bean.Offline;
import shop.services.manage.organize.OrganizeService;
import shop.services.manage.organize.bean.Organize;
import shop.services.manage.organizeRelation.OrganizeRelationService;
import shop.services.manage.organizeRelation.bean.OrganizeRelation;
import shop.services.manage.system.bean.Role;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.RoleService;
import shop.services.manage.system.impl.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description 机构管理
 * @Author semstouch
 * @Date 2017/4/15
 **/
@Controller
@RequestMapping("/manage/organize/")
public class OrganizeAction extends BaseController<Organize> {
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private OfflineService offlineService;
    @Autowired
    private UserService userService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private RoleService roleService;

    @Override
    public Services<Organize> getService() {
        return organizeService;
    }

    private static final String page_toList = "/manage/organize/organizeManage";
    private static final String page_toEdit = "/manage/organize/organizeManageEdit";
    private static final String page_toAdd = "/manage/organize/organizeAdd";
    private static final String page_toAut = "/manage/organize/organizeAut";
    private static final String page_toAutFalse = "/manage/organize/organizeAutFalse";
    private static final String page_toCheck = "/manage/organize/organizeCheck";
    private static final String page_toCheckDetails = "/manage/organize/organizeCheckDetails";
    private static final String page_toCheckEdit = "/manage/organize/organizeCheckEdit";
    private static final String page_toAccountList = "/manage/organize/organizeVolunteerList";
    private static final String page_toAccountEdit = "/manage/organize/organizeVolunteerDetails";
    private static final String page_toOfflineList = "/manage/organize/organizeOfflineList";
    private static final String page_toOfflineEdit = "/manage/organize/organizeOfflineDetails";
    private static final String page_toMyOrganize = "/manage/organize/organizeMyDetails";
    private static final String page_toAA = "/manage/volunteer/volunteerCheck";
    private static final String page_toAB = "/manage/volunteer/volunteerList";
    private static final String page_toAC = "/manage/volunteer/volunteerDetails";

    private OrganizeAction() {
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }

    //佣金模块跳转方法（未完善）
    @RequestMapping("/toAA")
    public String toAA() {
        return page_toAA;
    }

    //佣金模块跳转方法（未完善）
    @RequestMapping("/toAB")
    public String toAB() {
        return page_toAB;
    }

    //佣金模块跳转方法（未完善）
    @RequestMapping("/toAC")
    public String toAC() {
        return page_toAC;
    }


    /**
     * 跳转到我的机构页面
     *
     * @return
     */
    @RequestMapping("toMyOrganize")
    public String toMyOrganize() {
        return page_toMyOrganize;
    }

    /**
     * 跳转到机构认证页面
     *
     * @return
     */
    @RequestMapping("toAut")
    public String toAut() {
        return page_toAut;
    }

    /**
     * 跳转到认证失败页面
     *
     * @return
     */
    @RequestMapping("toAutFalse")
    public String toAutFalse() {
        return page_toAutFalse;
    }

    /**
     * 跳转到机构审核列表页面
     *
     * @return
     */
    @RequestMapping("toCheck")
    public String toCheck() {
        return page_toCheck;
    }


    /**
     * 跳转到机构志愿者列表页面
     *
     * @return
     */
    @RequestMapping("toAccountList")
    public String toAccountList(HttpServletRequest request, @ModelAttribute("account") Account account) throws Exception {
        account.clear();
        return page_toAccountList;
    }

    /**
     * 跳转到机构活动列表页面
     *
     * @return
     */
    @RequestMapping("toOfflineList")
    public String toOfflineList(HttpServletRequest request, @ModelAttribute("offline") Offline offline) throws Exception {
        offline.clear();
        return page_toOfflineList;
    }

    /**
     * 跳转到机构审核详情页面
     *
     * @param organize
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toCheckEdit")
    public String toCheckEdit(@ModelAttribute("organize") Organize organize, ModelMap model) throws Exception {
        organize = organizeService.selectOne(organize);
        model.addAttribute("organize", organize);
        return page_toCheckEdit;
    }


    /**
     * 跳转到机构活动详情页面
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toOfflineEdit")
    public String toOfflineEdit(@ModelAttribute("e") Offline e, ModelMap model) throws Exception {
        e = offlineService.selectOne(e);
        model.addAttribute("e", e);
        return page_toOfflineEdit;
    }

    /**
     * 跳转到机构审核查看
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toCheckDetails")
    public String toCheckDetails(@ModelAttribute("e") Organize e, ModelMap model) throws Exception {
        e = organizeService.selectOne(e);
        model.addAttribute("e", e);
        return page_toCheckDetails;
    }

    /**
     * 跳转到机构志愿者详情页面
     *
     * @param e
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("toAccountEdit")
    public String toAccountEdit(@ModelAttribute("e") Account e, ModelMap model) throws Exception {
        e = accountService.selectOne(e);
        model.addAttribute("e", e);
        return page_toAccountEdit;
    }

    /**
     * 跳转到机构注册页面
     * @return
     */
    @RequestMapping("toRegisterOrganize")
    public String toRegisterOrganize() {
        return "/manage/system/registerOrganize";
    }


    /**
     * 机构认证（查询机构数据）
     *
     * @param organize
     * @return
     */
    @RequestMapping(value = "selectOrganizeDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrganizeDetail(HttpServletRequest request, Organize organize) {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize rs = new Organize();
        rs.setPrincipalPhone(user.getUsername());
        rs = organizeService.selectOne(rs);
        if (rs.getStatus().equals("3") || rs.getStatus().equals("2")) {//未认证和不通过机构可以进行认证操作
            organize = organizeService.selectOne(organize);
            jsonResult.setData(organize);
            return jsonResult;
        } else if (rs.getStatus().equals("0")) {
            jsonResult.setMessage("您已进行过认证操作，请耐心等待审核结果！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else {
            jsonResult.setMessage("您已通过审核，无需再进行认证！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }

    /**
     * 查看我的机构
     *
     * @param organize
     * @return
     */
    @RequestMapping(value = "selectMyOrganize", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectMyOrganize(HttpServletRequest request, Organize organize) {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize rs = new Organize();
        rs.setPrincipalPhone(user.getUsername());
        rs = organizeService.selectOne(rs);
        if (rs.getStatus().equals("3")) {
            jsonResult.setMessage("您还未进行认证，无法查看信息！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else if (rs.getStatus().equals("2")) {
            jsonResult.setMessage("您的信息不符合要求，请重新提交认证资料！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else if (rs.getStatus().equals("0")) {
            jsonResult.setMessage("您的资料正在审核，暂时无法查看信息！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else {
            jsonResult.setData(rs);
            return jsonResult;
        }
    }

    /**
     * 查询全部机构（绑定上级查询数据）
     *
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @RequestMapping("selectOrganizeList")
    @ResponseBody
    public JSONResult selectOrganizeList(HttpServletRequest request, @ModelAttribute("e") Organize e) throws Exception {
        List<Organize> rsList = getService().selectList(e);
        jsonResult = new JSONResult();
        if (!e.getRank().equals("")) {
            jsonResult.setData(rsList);
        }
        return jsonResult;
    }

    /**
     * 查询下级机构
     *
     * @param request
     * @param organize
     * @return
     * @throws Exception
     */
    @RequestMapping("selectSubList")
    @ResponseBody
    public JSONResult selectSubList(HttpServletRequest request, @ModelAttribute("organize") Organize organize) throws Exception {
        List<Organize> rsList = organizeService.selectSubList(organize);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询上级机构
     *
     * @param request
     * @param organize
     * @return
     * @throws Exception
     */
    @RequestMapping("selectSupList")
    @ResponseBody
    public JSONResult selectSupList(HttpServletRequest request, @ModelAttribute("organize") Organize organize) throws Exception {
        List<Organize> rsList = organizeService.selectSupList(organize);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询基金总数（admin）
     *
     * @param request
     * @param organize
     * @return
     * @throws Exception
     */
    @RequestMapping("selectAdminFund")
    @ResponseBody
    public JSONResult selectAdminFund(HttpServletRequest request, @ModelAttribute("organize") Organize organize) throws Exception {
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        List<Organize> rsList = getService().selectList(organize);
        jsonResult = new JSONResult();
        if (!user.getRid().equals("1")) {
            jsonResult.setSuccess(false);
            return jsonResult;
        } else {
            jsonResult.setData(rsList);
            return jsonResult;
        }
    }

    /**
     * 查询基金总数（机构账号）
     * @param request
     * @param organize
     * @return
     */
    @RequestMapping(value = "selectOrganizeFund", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrganizeFund(HttpServletRequest request, Organize organize) {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize rs = new Organize();
        rs.setPrincipalPhone(user.getUsername());
        rs = organizeService.selectOne(rs);
        if (!user.getRid().equals("1")) {
            if(!rs.getStatus().equals("1")){
                jsonResult.setSuccess(false);
                return jsonResult;
            }else{
                jsonResult.setData(rs);
                return jsonResult;
            }
        }else{
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }


    /**
     * 机构认证方法
     *
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @RequestMapping("updateAutJson")
    @ResponseBody
    public JSONResult updateAutJson(HttpServletRequest request, @ModelAttribute("e") Organize e) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize rs = new Organize();
        rs.setPrincipalPhone(user.getUsername());
        rs = organizeService.selectOne(rs);
        if (rs.getStatus().equals("2") || rs.getStatus().equals("3")) {//未认证或者不通过机构可以进行认证操作
            e.setStatus("0");
            organizeService.update(e);
            jsonResult.setData(e.getStatus());
            return jsonResult;
        } else if (rs.getStatus().equals("1")) {
            jsonResult.setMessage("您已通过审核，无需再认证！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else {
            jsonResult.setMessage("您已进行过认证，请耐心等待审核结果！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }


    /**
     * 机构审核方法
     *
     * @param request
     * @param organize
     * @return
     * @throws Exception
     */
    @RequestMapping("updateOrganizeJson")
    @ResponseBody
    public JSONResult updateOrganizeJson(HttpServletRequest request, @ModelAttribute("organize") Organize organize, String contents) throws Exception {
        jsonResult = new JSONResult();
        QRcodeUtils qrCodeUtils = new QRcodeUtils();
        organize.setQrCode(qrCodeUtils.createQrcode(request, contents));
        OrganizeRelation organizeRelation = new OrganizeRelation();
        organizeRelation.setParentID(organize.getParentID());
        organizeRelation.setSonID(organize.getId());
        if (organize.getStatus().equals("1") && StringUtils.isBlank(organize.getRank())) {
            jsonResult.setMessage("您还未绑定等级，不能保存！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else {
            organizeService.update(organize);
            jsonResult.setData(organize.getStatus());
            organizeRelationService.insert(organizeRelation);
            return jsonResult;
        }
    }


    /**
     * 查询机构志愿者列表
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("loadAccountData")
    @ResponseBody
    public PagerModel loadAccountData(HttpServletRequest request, Account e) {
        int offset = 0;
        int pageSize = 10;
        if (e.getName() != null) {
            e.setPhone(e.getName());
        }
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = accountService.selectPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 查询机构活动列表
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("loadOfflineData")
    @ResponseBody
    public PagerModel loadOfflineData(HttpServletRequest request, Offline e) {
        int offset = 0;
        int pageSize = 10;
        if (e.getName() != null) {
            e.setPrincipal(e.getName());
        }
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = offlineService.selectPageList(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 查询机构列表
     *
     * @param request 请求
     * @param e       对象参数
     * @return 分页数据模型
     */
    @Override
    @RequestMapping("loadData")
    @ResponseBody
    public PagerModel loadData(HttpServletRequest request, Organize e) {
        int offset = 0;
        int pageSize = 10;
        if (e.getName() != null) {
            e.setPrincipal(e.getName());
        }
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        User user = (User) request.getSession().getAttribute(ManageContainer.manage_session_user_info);
        Organize organize = new Organize();
        organize.setPrincipalPhone(user.getUsername());
        organize = organizeService.selectOne(organize);
        PagerModel pager = null;
        if (!user.getRid().equals("1")) {
            if (!organize.getRank().equals("3")) {//限制C级机构显示机构数据
                e.setId(organize.getId());
                pager = organizeService.selectSubPageList(e);//查询下级机构
                pager.setRecordsTotal(pager.getTotal());
                pager.setRecordsFiltered(pager.getTotal());
            } else {
                return pager;
            }
        } else {
            pager = getService().selectPageList(e);
            pager.setRecordsTotal(pager.getTotal());
            pager.setRecordsFiltered(pager.getTotal());
        }
        return pager;
    }


    /**
     * 机构注册方法
     *
     * @param request
     * @param organize 信息
     * @return
     * @throws Exception
     */
    @Override
    @RequestMapping(value = "/insertJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertJson(HttpServletRequest request, @ModelAttribute("organize") Organize organize) throws Exception {
        jsonResult = new JSONResult();
        HttpSession session = request.getSession();
        // SmsId 短信唯一码   SmsContent 短信内容
        String smsId = request.getParameter("SmsId").toString();
        String smsContent = request.getParameter("SmsContent").toString();

        SMS sms = new SMS();
        SMSVerifyCodeResult rs = sms.verifyCode(smsId, smsContent);
        if (!rs.getSuccess()) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("短信验证码错误！");
            return jsonResult;
        }
        List<Account> accountList = accountService.selectList(new Account());
        List<User> userList = userService.selectList(new User());
        for (User anUserList : userList) {//循环遍历userList
            if (anUserList.getUsername().equals(organize.getPrincipalPhone())) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("该手机已注册过机构，不可重复注册");
                return jsonResult;
            }
        }
        for (Account anAccountList : accountList) {//循环遍历accountList
            if (anAccountList.getPhone().equals(organize.getPrincipalPhone())) {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("该手机已注册为志愿者，不可注册为机构");
                return jsonResult;
            }
        }
        organizeService.insert(organize);
//      插入用户表做登录验证
        User user = new User();
        user.setUsername(organize.getPrincipalPhone());
        user.setPassword(MD5.md5(request.getParameter("password")));
        //      绑定微信
        if (session.getAttribute("userOpenId") != null) {
            user.setOpenID(session.getAttribute("userOpenId").toString());
        }
//        获取角色信息
        Role role = roleService.selectByRoleName("机构账号");
        user.setRid(role.getId());
        user.setNickname(organize.getPrincipalPhone());
        user.setStatus("y");
        userService.insert(user);
        return jsonResult;
    }

    /**
     * 发送验证码
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getSMSCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult getSMSCode(HttpServletRequest request) throws Exception {
        JSONResult rs = new JSONResult();
        String mobile = request.getParameter("mobile");//给request塞值
        List<Account> accountList = accountService.selectList(new Account());
        List<User> userList = userService.selectList(new User());
        for (User anUserList : userList) {//循环遍历userList
            if (anUserList.getUsername().equals(mobile)) {
                rs.setSuccess(false);
                rs.setMessage("该手机已注册过机构，不可重复注册");
                return rs;
            }
        }
        for (Account anAccountList : accountList) {//循环遍历accountList
            if (anAccountList.getPhone().equals(mobile)) {
                rs.setSuccess(false);
                rs.setMessage("该手机已注册为志愿者，不可注册为机构");
                return rs;
            }
        }
        SMS sms = new SMS();
        rs.setData(sms.sendCode(mobile, "5kDaOD-SQ8AbS959Lb9QRE", "86", null, null));
        rs.setSuccess(true);
        return rs;
    }
}
